<?php


namespace app\index\model;


use app\index\common\Common;
use think\Db;
use think\Exception;
use think\Model;
use think\Session;

class Product extends Model
{

    public static $product_type=['1'=>'PC','2'=>'KG'];

    public static function getProductList($search_param,$page_param): array
    {
        $ProductClass = new self();

        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('product');
        if(!empty($group)){
            $warehouse_id=GroupWarehouse::getWareHouseByGroup($group);
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $warehouse_id=GroupWarehouse::getWareHouseByGroup($search_param['group_id']);
        }
        if(isset($warehouse_id) && !empty($warehouse_id)){
            $where['p.warehouse']=['in',$warehouse_id];
        }

        if(!empty($search_user)) {
            $where['p.create_user'] = ['in', $search_user];
        }else if(is_numeric($search_param['user_id'])){
            $search_user=[$search_param['user_id']];
            $where['p.create_user'] = ['in', $search_user];
        }
        if(!empty($search_param['vendor_id'])) {
            $where['p.vendor_id'] = ['=', $search_param['vendor_id']];
        }
        $where['p.del_flag']=['=',0];
        if (is_numeric($search_param['stock_warehouse'])) {
            $where['p.warehouse']=['=',$search_param['stock_warehouse']];
        }
        if (!empty($search_param['create_time'])) {
            $where['p.create_time']=['between',[$search_param['create_time'].' 00:00:00',$search_param['create_time'].' 23:59:59']];
        }
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            if($search_param['search_key'] === 'id'){
                $id=explode(' ',$search_param['search_value']);
                $where['p.'.$search_param['search_key']]=['in',$id];
            }else{
                $where[$search_param['search_key']]=['like','%'.$search_param['search_value'].'%'];
            }
        }

        $obj=$ProductClass
            ->alias('p')
            ->join('vendor v','p.vendor_id = v.id','left')
            ->where($where)
            ->field('p.id,p.cn_name,p.en_name,p.type,p.image,p.selling_price,p.amount,p.locked_quantity,p.demand_stock,p.pur_price,p.status,if(p.type=1,p.demand_stock-p.amount-p.in_transit_stock,0) purchase_number,p.in_transit_stock,v.company,p.vendor_id')
            ->order('p.create_time','desc')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);

        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['product'=>[],'total'=>0,'action_role'=>$action_role]];
        }
        $count=$obj->total();
        $data=$obj->items();
        foreach($data as $key=>$value){
            $data[$key]['type_text']=self::$product_type[$value['type']];
            $value['image_thumb'] = Common::getThumbImage($value['image']);
            $data[$key]['surplus_quantity']=round($value['amount']-$value['locked_quantity'],2);
            $data[$key]['balance_cost']=round($value['surplus_quantity']*$value['pur_price'],2);
            $data[$key]['purchase_number']=round($value['purchase_number'],2);
            if($value['purchase_number'] <0){
                $data[$key]['purchase_number'] = 0;
            }
        }
        return ['status'=>true,'result'=>['product'=>$data,'total'=>$count,'action_role'=>$action_role]];
    }

    /**
     * 获取采购列表
     * create by yhb on 2021/3/9 14:15
     * @param $search_param
     * @param $page_param
     * @return array
     * @throws \think\exception\DbException
     */
    public function getPurchaseList($search_param, $page_param)
    {

        $ProductClass = new self();

        $where['p.del_flag']=['=',0];
        $where['p.status']=['=',0];
        if (is_numeric($search_param['stock_warehouse'])) {
            $where['p.warehouse']=['=',$search_param['stock_warehouse']];
        }
        if (!empty($search_param['create_time'])) {
            $where['p.create_time']=['between',[$search_param['create_time'].' 00:00:00',$search_param['create_time'].' 23:59:59']];
        }
        if (!empty($search_param['vendor_list'])) {
            $where['p.vendor_id'] = ['=',$search_param['vendor_list']];
        }
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            if($search_param['search_key'] === 'id'){
                $where['p.'.$search_param['search_key']]=['=',$search_param['search_value']];
            }else{
                $where['p.'.$search_param['search_key']]=['like','%'.$search_param['search_value'].'%'];
            }
        }

        $obj=$ProductClass
            ->alias('p')
            ->join('vendor v','p.vendor_id = v.id','left')
            ->where($where)
            ->field('p.id,p.cn_name,p.en_name,p.type,p.amount,p.locked_quantity,p.pur_price,p.demand_stock,p.in_transit_stock,(p.demand_stock-p.amount-p.in_transit_stock) purchase_number,p.image,v.company,p.vendor_id')
            ->where('(p.demand_stock-p.amount-p.in_transit_stock)>=0')
            ->order('purchase_number','desc')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);

        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['product'=>[],'total'=>0]];
        }
        $count=$obj->total();
        $data=$obj->items();;
        foreach($data as $key=>$value){
            $data[$key]['type_text']=self::$product_type[$value['type']];
            $data[$key]['thumb_image']=Common::getThumbImage($value['image']);
            $data[$key]['surplus_quantity']=round($value['amount']-$value['locked_quantity'],2);
        }
        return ['status'=>true,'result'=>['product'=>$data,'total'=>$count]];
    }

    /**
     * 通过ids获取到商品数据列表
     * create by yhb on 2021/4/1 17:32
     * @param array $productId
     * @param array $vendorId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductByIds($productId= [],$vendorId = [])
    {
        if(count(array_unique($vendorId)) > 1){
            if(count($vendorId) === count(array_unique($vendorId))){
                return ['status'=>false,'result'=>'请确保它们时同一个供应商'];
            }
        }

        $ProductClass = new self();

        $data=$ProductClass->where('id','in',$productId)->where('del_flag',0)->field('id,cn_name,en_name,0 priority,vendor_id,image,type,warehouse,amount,demand_stock,(demand_stock-amount-in_transit_stock) purchase_number,pur_price,in_transit_stock')->select()->toArray();

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到商品'];
        }
        foreach($data as $key=>$value) {
            $data[$key]['type_text'] = self::$product_type[$value['type']];
            $data[$key]['priority'] = 0;
            $data[$key]['thumb_image'] = Common::getThumbImage($value['image']);
            if($value['purchase_number'] <0){
                $data[$key]['purchase_number'] = 0;
            }
        }

        return ['status'=>true,'result'=>['data'=>$data]];
    }

    /**
     * 通过id获取到商品数据
     * create by yhb on 2021/4/1 17:30
     * @param array $productId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductById($productId = [])
    {;
        $ProductClass = new self();

        $data=$ProductClass->where('id','=',$productId['id'])->where('del_flag',0)->field('id,cn_name,en_name,0 priority,vendor_id,image,type,warehouse,amount,demand_stock,(demand_stock-amount-in_transit_stock) purchase_number,pur_price,in_transit_stock')->select()->toArray();

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到商品'];
        }
        foreach($data as $key=>$value) {
            $data[$key]['type_text'] = self::$product_type[$value['type']];
            $data[$key]['priority'] = 0;
            $data[$key]['thumb_image'] = Common::getThumbImage($value['image']);
            if($value['purchase_number'] <0){
                $data[$key]['purchase_number'] = 0;
            }
        }

        return ['status'=>true,'result'=>['data'=>$data]];
    }

    /**
     * 获取ids相对性供应商信息
     * create by yhb on 2021/3/30 18:54
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductAll($id)
    {
        $ProductClass = new self();

        $obj=$ProductClass
            ->alias('p')
            ->join('vendor v','v.id = p.vendor_id','left')
            ->where('p.id','in',$id)
            ->where('p.del_flag',0)
            ->field('p.id,p.cn_name,p.en_name,v.company')
            ->select();

        if(empty($obj)){
            return ['status'=>false,'result'=>'未找到商品'];
        }else{
            $data = $obj->toArray();
        }

        return ['status'=>true,'result'=>['data'=>$data]];
    }

    public static function addGoods($data): array
    {
        $ProductClass = new self();
        $ProductPurHistoryClass=new ProductPurHistory();

        $repeat=$ProductClass->where(function ($query)use($data){
            $query->where('cn_name','=',$data['cn_name'])->whereOr('en_name','=',$data['en_name']);
        })->where('del_flag',0)->where('warehouse',$data['warehouse'])->field('id,cn_name,en_name')->find();
        if(!empty($repeat)){
            return ['status'=>false,'result'=>'商品名已被使用 '.' '.$repeat['cn_name'].' '.$repeat['en_name']];
        }

        $ProductClass->startTrans();
        try {
            $ProductClass->data($data);
            $result=$ProductClass->save();
            if($result===false){
                return ['status'=>false,'result'=>'添加失败'];
            }
            $ProductPurHistoryClass->data(['pro_id'=>$ProductClass->id,'pur_price'=>$data['pur_price'],'type'=>1,'amount'=>$data['amount'],'create_user'=>$data['create_user'],'vendor_id'=>$data['vendor_id']]);
            $result=$ProductPurHistoryClass->save();
            if($result===false){
                return ['status'=>false,'result'=>'保存历史失败'];
            }
            $ProductClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (\Exception $e) {
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }

    /**
     * 批量入库
     * create by yhb on 2021/4/2 11:55
     * @param $insert_product
     * @param $insert_product_history
     * @param $vendor
     * @return array|\think\response\Json
     * @throws \think\exception\PDOException
     */
    public static function createStockBatchIn($insert_product,$insert_product_history,$vendor)
    {
        $vendorClass = new Vendor();
        $productPurHistoryClass = new ProductPurHistory();
        $Product=new self();
        $Product->startTrans();
        try {
            if(!empty($vendor)){
                $obj = $vendorClass
                    ->where('company',$vendor)
                    ->where('del_flag',0)
                    ->field('id')
                    ->find();
                if(!empty($obj)){
                    $vendorId = $obj->toArray();
                }else{
                    $vendorId = [];
                    $insert_vendor = [
                        'company' => $vendor,
                    ];
                    $result = $vendorClass->save($insert_vendor);
                    if($result===false){
                        return ['status'=>false,'result'=>'添加供应商失败'];
                    }
                    $vendorId['id'] = $vendorClass->id;
                }
            }else{
                return ['status'=>false,'result'=>'选择供应商'];
            }

            foreach ($insert_product as $key=>$value){
                $insert_product[$key]['vendor_id'] = $vendorId['id'];
            }

            $result =  $Product->isUpdate(false)->saveAll($insert_product);
            if($result===false){
                return ['status'=>false,'result'=>'入库失败'];
            }
            foreach ($result as $k => $v) {
                $insert_product_history[$k]['pro_id'] = $v['id'];
                $insert_product_history[$k]['vendor_id'] = $vendorId['id'];
            }

            $result=$productPurHistoryClass->isUpdate(false)->saveAll($insert_product_history);
            if($result===false){
                return ['status'=>false,'result'=>'添加商品采购价历史失败'];
            }

            $Product->commit();
            return ['status'=>true,'result'=>'入库成功'];
        }catch (\Exception $e) {
            $Product->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }

    public static function getGoodsById($id): array
    {
        $ProductClass = new self();

        $data=$ProductClass->where('id',$id)->where('del_flag',0)->field('id,trim(cn_name) cn_name,trim(en_name) en_name,pur_price,amount,weight,type,warehouse,selling_price,image,introduction,remark,vendor_id,pur_price,multiple')->find();
        if(empty($data)){
            return ['status'=>false,'result'=>'未找到商品'];
        }

        $data['image_thumb']=Common::getThumbImage($data['image']);
        return ['status'=>true,'result'=>['data'=>$data]];
    }

    public static function getGoodsByGoodsId($id): array
    {
        $ProductClass = new self();

        $data=$ProductClass->where('id',$id)->where('del_flag',0)->field('id pro_id,id,cn_name,en_name,amount stock,type,weight')->find();
        if(empty($data)){
            return ['status'=>false,'result'=>'未找到商品'];
        }
        return ['status'=>true,'result'=>['data'=>$data]];
    }
    
    public static function getGoodsListByName($group,$cn_name='',$en_name=''): array
    {
        $ProductClass = new self();
        ['search_user'=>$search_user]=ActionRole::checkUserActionRole('product_search');
        if(!empty($search_user)) {
            $where['p.create_user']=['=',$search_user];
        }
        $warehouse_id=GroupWarehouse::getWareHouseByGroup($group);
        if(empty($warehouse_id)){
            return ['status'=>false,'result'=>''];
        }
        $where['p.warehouse']=['in',$warehouse_id];
        $where['p.del_flag']=['=',0];
        $where['p.status']=['=',0];

        if($cn_name!=='') {
            $where['p.cn_name']=['like','%' . $cn_name . '%'];
            $data = $ProductClass->alias('p')->join('stock_warehouse sw','p.warehouse=sw.id','left')->where($where)->field('p.id value,trim(p.cn_name) label,p.en_name translate,sw.name warehouse')->select()->toArray();
        }else if($en_name!==''){
            $where['p.en_name']=['like','%' . $en_name . '%'];
            $data = $ProductClass->alias('p')->join('stock_warehouse sw','p.warehouse=sw.id','left')->where($where)->field('p.id value,trim(p.en_name) label,p.cn_name translate,sw.name warehouse')->select()->toArray();
        }else{
            return ['status'=>false,'result'=>'未找到商品'];
        }

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到商品'];
        }

        return ['status'=>true,'result'=>['data'=>$data]];
    }
    public static function getGoodsListByEnName($en_name='',$cn_name=''): array
    {
        $ProductClass = new self();
        ['search_user'=>$search_user]=ActionRole::checkUserActionRole('product_search');
        if(!empty($search_user)) {
            $where['p.create_user']=['=',$search_user];
        }
        $where['p.del_flag']=['=',0];
        $where['p.status']=['=',0];

        if($en_name!==''){
            $where['p.en_name']=['like','%' . $en_name . '%'];
            $data = $ProductClass->alias('p')->join('stock_warehouse sw','p.warehouse=sw.id','left')->where($where)->field('p.id value,trim(p.en_name) label,p.cn_name translate,sw.name warehouse')->select()->toArray();
        }else{
            $where['p.cn_name']=['like','%' . $cn_name . '%'];
            $data = $ProductClass->alias('p')->join('stock_warehouse sw','p.warehouse=sw.id','left')->where($where)->field('p.id value,trim(p.cn_name) label,p.en_name translate,sw.name warehouse')->select()->toArray();
        }

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到商品'];
        }

        return ['status'=>true,'result'=>['data'=>$data]];
    }

    /**
     * getGoodsByName
     * 商品名获取商品id
     * @url
     * @method
     * @param int $warehouse
     * @param string $cn_name
     * @param string $en_name
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/3/16
     */
    public static function getGoodsByName($warehouse, $en_name='', $cn_name=''): array
    {
        $ProductClass=new self();
        $repeat = $ProductClass->where(function ($query) use ($cn_name,$en_name) {
            $query->where('cn_name', '=', $cn_name)->whereOr('en_name', '=', $en_name);
        })->where('del_flag', 0)->where('warehouse', $warehouse)->field('id,cn_name,en_name')->find();
        if (!empty($repeat)) {
            return ['status' => true, 'result' => ['msg'=>'商品名已被使用 ','cn_name'=>$repeat['cn_name'] ,'en_name'=>$repeat['en_name'],'id'=>$repeat['id']]];
        }
        return ['status'=>false,'result'=>'未找到商品'];
    }

    public static function updateGoodsStock($id,$data): array
    {
        $ProductClass = new self();
        $ProductPurHistory=new ProductPurHistory();

        $old_product=$ProductClass->where('id',$id)->field('amount,weight,type,pur_price,vendor_id')->find();

        $pur_price=round(($data['pur_price']*$data['amount']+$old_product['pur_price']*$old_product['amount'])/($data['amount']+$old_product['amount']),2);

        $update=['amount'=>$data['amount']+$old_product['amount'],'pur_price'=>$pur_price];

        $ProductClass->startTrans();
        try {
            $result=$ProductClass->save($update,['id' => $id]);
            if($result===false){
                return ['status'=>false,'result'=>'更新失败'];
            }
            $ProductPurHistory->data(['pro_id'=>$id,'pur_price'=>$data['pur_price'],'amount'=>$data['amount'],'create_user'=>$data['create_user'],'type'=>1,'vendor_id'=>$old_product['vendor_id']]);
            $result=$ProductPurHistory->save();
            if($result===false){
                return ['status'=>false,'result'=>'保存历史失败'];
            }
            $ProductClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (\Exception $e) {
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败'.$e->getMessage()];
        }
    }

    public static function updateGoodsPrice($id,$price):array
    {
        $ProductClass = new self();
        $old_product=$ProductClass->where('id',$id)->field('id,selling_price')->find();

        if($old_product['selling_price']==$price){
            return ['status'=>true,'result'=>'未修改价格'];
        }
        $ProductClass->startTrans();
        try {
            $result=$ProductClass->save(['selling_price'=>$price],['id' => $id]);

            if($result===false){
                return ['status'=>false,'result'=>'更新失败'];
            }

            $ProductClass->commit();
            return ['status'=>true,'result'=>'更新价格成功'];
        }catch (\Exception $e) {
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新价格失败'.$e->getMessage()];
        }
    }

    public static function stockOutByInvoice($stock_out,$stock_pro_id,$order_id,$type){
        $ProductClass=new self();
        $ProductPurHistory=new ProductPurHistory();
        $OrderClass=new Order();
        $itemClass=new OrderItem();
        $itemDetailClass=new OrderItemDetail();

        $order_data = $OrderClass->alias('o')
            ->join('waybill w','o.waybill_id=w.id','left')
            ->where('o.id', 'in', $order_id)
            ->where('o.del_flag','=',0)
            ->field('o.id,o.stock_status,w.customer_name,o.waybill_id,w.ship_no,w.image,o.create_user,o.create_group')
            ->select()->toArray();
        if(empty($order_data)){
            return ['status'=>false,'result'=>'未找到对应账单'];
        }
        if($type===1 && empty($order_data[0]['image'])){
            return ['status'=>false,'result'=>'先上传图片'];
        }
        foreach ($order_data as $key=>$value){
            if(!$value['waybill_id']){
                return ['status'=>false,'result'=>'账单不可出库'];
            }
            if($value['stock_status']===2){
                return ['status'=>false,'result'=>'账单已出库'];
            }
        }

        $ProductClass->startTrans();
        try {
            $stock = $ProductClass->where('id','in', $stock_pro_id)->field('id,amount,weight,selling_price,demand_stock,locked_demand_stock,locked_quantity,vendor_id')->lock(true)->select()->toArray();
            $stock_pro_list=[];
            foreach ($stock as $key=>$value){
                $stock_pro_list[$value['id']]=['id'=>$value['id'],'amount'=>$value['amount'],'demand_stock'=>$value['demand_stock'],'locked_demand_stock'=>$value['locked_demand_stock'],'locked_quantity'=>$value['locked_quantity'],'vendor_id'=>$value['vendor_id']];
            }
            $insert_product_history=[];
//            $update_pro_list=[];
            $update_item_list=[];
            $update_detail_list=[];
            foreach ($stock_out as $key=>$value){
                if(isset($stock_pro_list[$value['pro_id']])){
                    $arr=&$stock_pro_list[$value['pro_id']];
                    if($arr['amount']<$value['stock_out_amount']){
                        return ['status' => false, 'result' => $value['cn_name'] . '库存不足'];
                    }
                    if ($value['type']==1){
                        if ($value['isChildren']){
                            $detail_demand_stock=0;
                            $detail_lock_quantity=0;
                            $update_detail_list[$value['id']]=['id'=>$value['id'],'demand_stock'=>$detail_demand_stock,'lock_quantity'=>$detail_lock_quantity];
                        }else{
                            $item_demand_stock=0;
                            $item_lock_quantity=0;
                            $update_item_list[$value['id']]=['id'=>$value['id'],'demand_stock'=>$item_demand_stock,'lock_quantity'=>$item_lock_quantity];
                        }
                        $arr['amount'] -= $value['stock_out_amount'];
                        $arr['demand_stock'] -= $value['stock_out_amount'];
                        $arr['locked_demand_stock'] -= $value['stock_out_amount'];
                        $arr['locked_quantity'] -= $value['stock_out_amount'];
//                        $update_pro_list[$value['pro_id']]=['id'=>$value['pro_id'],'amount'=>$amount,'demand_stock'=>$demand_stock,'locked_quantity'=>$locked_quantity,'locked_demand_stock'=>$locked_demand_stock];
                    }else{
                        if ($value['isChildren']){
                            $detail_weight=$value['stock_out_amount'];
                            $update_detail_list[$value['id']]=['id'=>$value['id'],'weight'=>$detail_weight];
                        }else{
                            $item_weight=$value['stock_out_amount'];
                            $update_item_list[$value['id']]=['id'=>$value['id'],'weight'=>$item_weight];
                        }
                        $arr['amount'] -= $value['stock_out_amount'];
//                        $update_pro_list[$value['pro_id']]=['id'=>$value['pro_id'],'amount'=>$amount];
                    }
                }else{
                    return ['status' => false, 'result' => $value['show_index'].' '.$value['cn_name'] . '未找到库存'];
                }
//                $arr['amount']=$arr['amount']-$value['stock_out_amount'];
                $insert_product_history[]=['pro_id'=>$value['pro_id'],'pur_price'=>$value['pur_price'],'selling_price'=>$value['selling_price'],'amount'=>$value['stock_out_amount'],'type'=>2,'create_user'=>session('Login_user')['id'],'order_id'=>$value['order_id'],'order_item_id'=>$value['order_item_id']??0,'vendor_id'=>$arr['vendor_id']];
            }
            if(!empty($insert_product_history)){
                $result=$ProductPurHistory->insertAll($insert_product_history);
                if($result===false){
                    return ['status'=>false,'result'=>'商品出库记录写入失败'];
                }
            }
            if (!empty($stock_pro_list)){
                $result=$ProductClass->isUpdate()->saveAll($stock_pro_list);
                if($result===false){
                    return ['status'=>false,'result'=>'商品写入失败'];
                }
            }
            $result=$OrderClass->whereIn('id',$order_id)->update(['stock_status'=>2]);
            if($result===false){
                return ['status'=>false,'result'=>'订单状态修改失败'];
            }
            $result=$itemClass->isUpdate()->saveAll($update_item_list);
            if($result===false){
                return ['status'=>false,'result'=>'订单商品写入失败'];
            }
            if (!empty($update_detail_list)){
                $result=$itemDetailClass->isUpdate()->saveAll($update_detail_list);
                if($result===false){
                    return ['status'=>false,'result'=>'商品详情写入失败'];
                }
            }

            if($type===1){
                try {
                    $group = $order_data[0]['create_group'];
                    $user = $order_data[0]['create_user'];
                    $NewsClass=new News();
                    $content='运单已出库';
                    $NewsClass->isUpdate(false)->save(['type'=>2,'waybill_id'=>$order_data[0]['waybill_id'],'content'=>$content,'group'=>$group]);
                    Common::paymentNotice($user, $group, [
                        'type' => 'push',
                        'key' => 'home_waybill_list',
                        'msg' => $content,
                        'data' => [
                            'content'=>$content,
                            'customer_name' => $order_data[0]['customer_name'],
                            'waybill' => $order_data[0]['ship_no'],
                            'logistics_company' => '',
                            'logistics_waybill' => '',
                            'is_new' => true,
                        ]],'order');
                }catch (Exception $e){
                    trace('ipn payment notice error'.$e->getMessage(),'error');
                }
            }

            $ProductClass->commit();
            return ['status'=>true,'result'=>'出库成功'];
        }catch (Exception $e){
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return ['status' => false, 'result' =>'出库失败'.$e->getMessage()];
        }
    }

    /**
     * lockStockByOrder
     * 计算付款订单锁定库存
     * @url
     * @method
     * @param $order_id
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/8
     */
    public static function lockStockByOrder($order_id): array
    {
        $OrderClass=new Order();
        $OrderItemClass=new OrderItem();
        $OrderItemDetailClass=new OrderItemDetail();
        $ProductClass=new self();

        $order=$OrderClass
            ->where('id',$order_id)
            ->where('del_flag',0)
            ->where('stock_status',1)
            ->where('pay_type','in',[4,6])
            ->where('logistics_status','in',[0,1])
            ->field('pay_type,stock_status')->find();
        if(empty($order)){
            return ['status'=>false,'result'=>'未找到订单'];
        }
        $order_item=$OrderItemClass->where('order_id',$order_id)->where('del_flag',0)->field('id,pro_id,type,amount,demand_stock,lock_quantity')->select()->toArray();
        $order_item_id=[];
        $pro_ids=[];
        foreach ($order_item as $Key=>$value){
            $order_item_id[]=$value['id'];
            $pro_ids[]=$value['pro_id'];
        }

        $order_item_detail=$OrderItemDetailClass->where('order_item_id','in',$order_item_id)->where('del_flag',0)->field('id,order_item_id,type,pro_id,amount,demand_stock,lock_quantity')->select();
        $order_item_detail_list=[];
        foreach ($order_item_detail as $key=>$value) {
            $pro_ids[] = $value['pro_id'];
            $order_item_detail_list[$value['order_item_id']][]=$value;
        }
        $ProductClass->startTrans();
        try {
            $stock_list = $ProductClass->where('id', 'in', $pro_ids)->where('del_flag', 0)->lock(true)->column('amount,type,demand_stock,locked_demand_stock,type,locked_quantity', 'id');
            $update_order_item = [];
            $update_order_item_detail = [];
            $logistics_status=1;
            foreach ($order_item as $key => $value) {
                $lock_status=1;
                if ($value['pro_id']) {
                    $arr =& $stock_list[$value['pro_id']];
                    ['demand_stock' => $demand_stock, 'locked_stock' => $locked_stock, 'stock_locked_stock' => $stock_locked_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock] = Common::lockedStock($arr, $value);

                    $value['demand_stock'] += $demand_stock;
                    $value['lock_quantity'] += $locked_stock;

                    if($value['type']===1 && $value['amount']!=$value['lock_quantity']){
                        $lock_status=0;
                        $logistics_status=0;
                    }

                    $update_order_item[] = ['id' => $value['id'], 'demand_stock' => $value['demand_stock'], 'lock_quantity' => $value['lock_quantity'],'lock_status'=>$lock_status];
                    $arr['locked_quantity'] = $stock_locked_stock;
                    $arr['locked_demand_stock'] += $stock_locked_demand_stock;
                } else {
                    if(!isset($order_item_detail_list[$value['id']])){
                        $update_order_item[]=['id'=>$value['id'],'lock_status'=>$lock_status];
                        continue;
                    }
                    $lock_detail_status=1;
                    foreach ($order_item_detail_list[$value['id']] as $i => $item) {
                        $arr =& $stock_list[$item['pro_id']];
                        ['demand_stock' => $demand_stock, 'locked_stock' => $locked_stock, 'stock_locked_stock' => $stock_locked_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock] = Common::lockedStock($arr, $item);
                        $item['demand_stock'] += $demand_stock;
                        $item['lock_quantity'] += $locked_stock;
                        if($item['type']===1 && $item['amount']!=$item['lock_quantity']){
                            $lock_detail_status=0;
                            $lock_status=0;
                            $logistics_status=0;
                        }
                        $update_order_item_detail[] = ['id' => $item['id'], 'demand_stock' => $item['demand_stock'], 'lock_quantity' => $item['lock_quantity'],'lock_status'=>$lock_detail_status];
                        $arr['locked_quantity'] = $stock_locked_stock;
                        $arr['locked_demand_stock'] += $stock_locked_demand_stock;
                    }
                    $update_order_item[]=['id'=>$value['id'],'lock_status'=>$lock_status];
                }
            }
            $update_order=['id'=>$order_id,'logistics_status'=>$logistics_status];
            $result=$OrderClass->save($update_order,['id'=>$order_id]);
            if($result===false){
                return ['status'=>false,'result'=>'更新订单失败'];
            }
            $result=$OrderItemClass->isUpdate()->saveAll($update_order_item);
            if($result===false){
                return ['status'=>false,'result'=>'更新订单锁定库存失败'];
            }
            $result=$OrderItemDetailClass->isUpdate()->saveAll($update_order_item_detail);
            if($result===false){
                return ['status'=>false,'result'=>'更新订单详情锁定库存失败'];
            }
            $result=$ProductClass->isUpdate()->allowField(['id','demand_stock','locked_quantity'])->saveAll($stock_list);
            if($result===false){
                return ['status'=>false,'result'=>'更新商品锁定库存失败'];
            }
            $ProductClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (Exception $e){
            $ProductClass->rollback();
            trace('lock stock error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新库存失败'];
        }
    }

    /**
     * lockStockByProduct
     * 计算入库商品锁定库存
     * @url
     * @method
     * @param int $pro_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/8
     */
    public static function lockStockByProduct($pro_id): array{
        $OrderClass=new Order();
        $OrderItemClass=new OrderItem();
        $OrderItemDetailClass=new OrderItemDetail();
        $ProductClass=new self();
        $order_data=$OrderClass->alias('o')
            ->join('order_item oi','o.id=oi.order_id','left')
            ->join('order_item_detail oid','oi.id=oid.order_item_id','left')
            ->where(function ($query)use($pro_id){$query->where('oi.pro_id',$pro_id)->whereOr('oid.pro_id',$pro_id);})
            ->where('o.del_flag',0)
            ->where('oi.del_flag',0)
            ->where('o.stock_status',1)
            ->where('o.logistics_status','in',[0,1])
            ->where('o.pay_type','in',[4,6])
            ->where('oi.lock_status',0)
            ->order('o.payment_time,o.create_time')
            ->field('oi.id item_id,oi.order_id,oi.pro_id,oi.id,oi.amount,oi.demand_stock,oi.lock_quantity,oid.id detail_id,oid.demand_stock detail_demand_stock,oid.lock_quantity detail_lock_quantity,oid.amount detail_amount')
            ->select()->toArray();
        if(empty($order_data)){
            return ['status'=>true,'result'=>'没有订单需求'];
        }
        $ProductClass->startTrans();
        try {
            $stock = $ProductClass->where('id', $pro_id)->lock(true)->field('id,amount,demand_stock,locked_quantity,locked_demand_stock,type')->find();
            if (empty($stock)) {
                return ['status' => false, 'result' => '没有找到商品'];
            }
            $stock = $stock->toArray();
            if ($stock['type'] === 2) {
                return ['status' => true, 'result' => '不计算库存'];
            }
            $update_order_item = [];
            $update_order_item_detail = [];
            $order_id = [];
            $item_id = [];
            foreach ($order_data as $key => $value) {
                $lock_status = 1;
                if ($stock['amount'] - $stock['locked_quantity'] <= 0) {
                    break;
                }
                if ($value['pro_id']) {
                    $items = ['type' => $stock['type'], 'demand_stock' => $value['demand_stock'], 'lock_quantity' => $value['lock_quantity'], 'amount' => $value['amount']];
                    ['demand_stock' => $demand_stock, 'locked_stock' => $locked_stock, 'stock_locked_stock' => $stock['locked_quantity'],'stock_locked_demand_stock'=>$stock['locked_demand_stock']] = Common::lockedStock($stock, $items);

                    $value['demand_stock'] += $demand_stock;
                    $value['lock_quantity'] += $locked_stock;
                    if ($value['amount'] != $value['lock_quantity']) {
                        $lock_status = 0;
                    }
                    if ($lock_status === 1) {
                        $order_id[] = $value['order_id'];
                    }
                    $update_order_item[] = ['id' => $value['item_id'], 'demand_stock' => $value['demand_stock'], 'lock_quantity' => $value['lock_quantity'], 'lock_status' => $lock_status];
                } elseif($value['detail_id']) {
                    $items = ['type' => $stock['type'], 'demand_stock' => $value['detail_demand_stock'], 'lock_quantity' => $value['detail_lock_quantity'], 'amount' => $value['detail_amount']];
                    ['demand_stock' => $demand_stock, 'locked_stock' => $locked_stock, 'stock_locked_stock' => $stock['locked_quantity'],'stock_locked_demand_stock'=>$stock['locked_demand_stock']] = Common::lockedStock($stock, $items);

                    $value['detail_demand_stock'] += $demand_stock;
                    $value['detail_lock_quantity'] += $locked_stock;
                    if ($value['detail_amount'] != $value['detail_lock_quantity']) {
                        $lock_status = 0;
                    }
                    if ($lock_status === 1) {
                        $item_id[] = $value['item_id'];
                        $order_id[] = $value['order_id'];
                    }
                    $update_order_item_detail[] = ['id' => $value['detail_id'], 'demand_stock' => $value['detail_demand_stock'], 'lock_quantity' => $value['detail_lock_quantity'], 'lock_status' => $lock_status];
                }
            }
            $result=$OrderItemClass->isUpdate()->saveAll($update_order_item);
            if($result===false){
                throw Exception('更新订单商品失败');
            }
            $result=$OrderItemDetailClass->isUpdate()->saveAll($update_order_item_detail);
            if($result===false){
                throw Exception('更新订单商品详情失败');
            }
            $result=$ProductClass->allowField(['id','demand_stock','locked_quantity'])->isUpdate()->save($stock,['id'=>$pro_id]);
            if($result===false){
                throw Exception('更新库存信息失败');
            }

            if(!empty($item_id)){
                $item_id=array_unique($item_id);
                $order_item_detail=$OrderItemDetailClass->where('order_item_id','in',$item_id)->where('del_flag',0)->field('id,order_item_id,lock_status,type')->select()->toArray();
                foreach ($order_item_detail as $key=>$value){
                    if($value['lock_status']===0 && $value['type']===1){
                        $index=array_search($value['order_item_id'],$item_id);
                        if(isset($item_id[$index])){
                            unset($item_id[$index]);
                        }
                    }
                }
                if(!empty($item_id)) {
                    $result = $OrderItemClass->where('id', 'in', $item_id)->update(['lock_status' => 1]);
                    if ($result === false) {
                        throw Exception('更新账单商品锁定状态失败');
                    }
                }
            }

            if(!empty($order_id)){
                $order_id=array_unique($order_id);
                $order_item=$OrderItemClass->where('order_id','in',$order_id)->where('del_flag',0)->field('id,order_id,lock_status,type')->select()->toArray();
                foreach ($order_item as $key=>$value){
                    if($value['lock_status']===0 && $value['type']===1){
                        $index=array_search($value['order_id'],$order_id);
                        if(isset($order_id[$index])){
                            unset($order_id[$index]);
                        }
                    }
                }
                if(!empty($order_id)) {
                    $result = $OrderClass->where('id', 'in', $order_id)->update(['logistics_status' => 1]);
                    if ($result === false) {
                        throw Exception('更新账单锁定状态失败');
                    }
                }
            }
            $ProductClass->commit();
            return ['status'=>true,'result'=>'锁定库存成功'];
        }catch(Exception $e){
            $ProductClass->rollback();
            trace('lock stock product error'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'lock stock product error'.$e->getMessage()];
        }
    }

    /**
     * demandStockByProduct
     * 计算锁定需求库存
     * @url
     * @method
     * @param array $pro_id 商品id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/8
     */
    public static function demandStockByProduct($pro_id): array
    {
        $CustomerOrderClass=new CustomerOrder();
        $CustomerOrderDetailClass=new CustomerOrderDetail();
        $OrderClass=new Order();
        $OrderItemClass=new OrderItem();
        $OrderItemDetailClass=new OrderItemDetail();
        $ProductClass=new self();
        $customer_order=$CustomerOrderClass->alias('co')
            ->join('customer_order_detail cod','co.id=cod.customer_order_id','left')
            ->where('co.status',0)
            ->where('co.del_flag',0)
            ->where(function ($query)use($pro_id){
                $query->where('co.pro_id','in',$pro_id)->whereOr('cod.pro_id','in',$pro_id);
            })
            ->field('co.id,co.amount,co.pro_id,co.demand_stock,cod.id detail_id,cod.pro_id detail_pro_id,cod.amount detail_amount,cod.demand_stock detail_demand_stock')
            ->select()->toArray();

        $order_data=$OrderClass->alias('o')
            ->join('order_item oi','o.id=oi.order_id','left')
            ->join('order_item_detail oid','oi.id=oid.order_item_id','left')
            ->where(function ($query)use($pro_id){$query->where('oi.pro_id','in',$pro_id)->whereOr('oid.pro_id','in',$pro_id);})
            ->where('o.del_flag',0)
            ->where('o.pay_type','in',[0,1,2,3,4])
            ->where('o.logistics_status','in',[0,1])
            ->where('o.stock_status','=',1)
            ->order('o.create_time')
            ->field('oi.id,oi.pro_id,oi.amount,oi.demand_stock,oid.id detail_id,oid.pro_id detail_pro_id,oid.demand_stock detail_demand_stock,oid.amount detail_amount')
            ->select()->toArray();
        if(empty($order_data) && $customer_order){
            return ['status'=>true,'result'=>'没有订单需求'];
        }
        $ProductClass->startTrans();
        try {
            $stock_list = $ProductClass->where('id','in', $pro_id)->where('type',1)->lock(true)->column('amount,demand_stock,locked_demand_stock,type','id');
            if (empty($stock_list)) {
                $ProductClass->rollback();
                return ['status'=>true,'result'=>'没有订单需求'];
            }
            if(!empty($customer_order)){
                $update_customer_order=[];
                $update_customer_order_detail=[];
                foreach ($customer_order as $key=>$value){
                    if($value['pro_id']){
                        if(!isset($stock_list[$value['pro_id']])){continue;}
                        $stock=&$stock_list[$value['pro_id']];
                        ['demand_stock'=>$demand_stock,'stock_locked_demand_stock'=>$stock['locked_demand_stock']]=Common::demandStock($stock,$value['amount']-$value['demand_stock']);
                        $value['demand_stock']+=$demand_stock;
                        $update_customer_order[]=['id'=>$value['id'],'demand_stock'=>$value['demand_stock']];
                    }elseif($value['detail_id']){
                        if(!isset($stock_list[$value['detail_pro_id']])){continue;}
                        $stock=&$stock_list[$value['detail_pro_id']];
                        ['demand_stock'=>$demand_stock,'stock_locked_demand_stock'=>$stock['locked_demand_stock']]=Common::demandStock($stock,$value['detail_amount']-$value['detail_demand_stock']);
                        $value['detail_demand_stock']+=$demand_stock;
                        $update_customer_order_detail[]=['id'=>$value['detail_id'],'demand_stock'=>$value['detail_demand_stock']];
                    }
                }
                if(!empty($update_customer_order)){
                    $result=$CustomerOrderClass->isUpdate()->saveAll($update_customer_order);
                    if($result===false){
                        throw Exception('保存订单失败');
                    }
                }
                if(!empty($update_customer_order_detail)){
                    $result=$CustomerOrderDetailClass->isUpdate()->saveAll($update_customer_order_detail);
                    if($result===false){
                        throw Exception('保存订单商品详情');
                    }
                }
            }
            if(!empty($order_data)){
                $update_order=[];
                $update_order_detail=[];
                foreach ($order_data as $key=>$value){
                    if($value['pro_id']){
                        if(!isset($stock_list[$value['pro_id']])){continue;}
                        $stock=&$stock_list[$value['pro_id']];
                        ['demand_stock'=>$demand_stock,'stock_locked_demand_stock'=>$stock['locked_demand_stock']]=Common::demandStock($stock,$value['amount']-$value['demand_stock']);
                        $value['demand_stock']+=$demand_stock;
                        $update_order[]=['id'=>$value['id'],'demand_stock'=>$value['demand_stock']];
                    }elseif($value['detail_id']){
                        if(!isset($stock_list[$value['detail_pro_id']])){continue;}
                        $stock=&$stock_list[$value['detail_pro_id']];
                        ['demand_stock'=>$demand_stock,'stock_locked_demand_stock'=>$stock['locked_demand_stock']]=Common::demandStock($stock,$value['detail_amount']-$value['detail_demand_stock']);
                        $value['detail_demand_stock']+=$demand_stock;
                        $update_order_detail[]=['id'=>$value['detail_id'],'demand_stock'=>$value['detail_demand_stock']];
                    }
                }
                if(!empty($update_order)){
                    $result=$OrderItemClass->isUpdate()->saveAll($update_order);
                    if($result===false){
                        throw Exception('保存账单商品失败');
                    }
                }
                if(!empty($update_order_detail)){
                    $result=$OrderItemDetailClass->isUpdate()->saveAll($update_order_detail);
                    if($result===false){
                        throw Exception('保存账单商品详情失败');
                    }
                }
            }
            $result=$ProductClass->allowField(['id','locked_demand_stock'])->isUpdate()->saveAll($stock_list);
            if($result===false){
                throw Exception('保存库存失败');
            }
            $ProductClass->commit();
            return ['status'=>true,'result'=>'校验成功'];
        }catch (Exception $e){
            $ProductClass->rollback();
            trace('demandStockByProduct error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'校验失败'.$e->getMessage()];
        }
    }

    public static function getGoodsByNames($name)
    {
        $ProductClass=new self();
        $result=$ProductClass
            ->where('cn_name|en_name','like',$name.'%')
            ->where('del_flag',0)
            ->select();
        if(empty($result)){
            return ['status'=>false,'result'=>'未找到商品'];
        }
        return ['status'=>true,'result'=>['data'=>$result]];
    }

    /**
     * 隐藏商品
     * create by yhb on 2021/3/26 14:03
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hideProduct($data = [])
    {
        $productClass = new self();
        if(!empty($data)){
            $obj = $productClass->where('id',$data['id'])->where('del_flag',0)->find();
            if(empty($obj)){
                return ['status'=>false,'result'=>'未找到商品'];
            }
        }else{
            return ['status'=>false,'result'=>'没有相对应的商品'];
        }

        $result = $productClass->where('id',$data['id'])->where('del_flag',0)->update(['status'=>1]);
        if($result===false){
            return ['status'=>false,'result'=>'隐藏失败'];
        }
        return ['status'=>true,'result'=>'隐藏成功'];
    }

    /**
     * 展示商品
     * create by yhb on 2021/3/26 14:03
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exhibitionProduct($data = [])
    {
        $productClass = new self();
        if(!empty($data)){
            $obj = $productClass->where('id',$data['id'])->where('del_flag',0)->find();
            if(empty($obj)){
                return ['status'=>false,'result'=>'未找到商品'];
            }
        }else{
            return ['status'=>false,'result'=>'没有相对应的商品'];
        }

        $result = $productClass->where('id',$data['id'])->where('del_flag',0)->update(['status'=>0]);
        if($result===false){
            return ['status'=>false,'result'=>'展示失败'];
        }
        return ['status'=>true,'result'=>'展示成功'];
    }

    /**
     * 批量更新供应商
     * create by yhb on 2021/3/31 11:58
     * @param $data
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateProductAll($data)
    {
        $productClass=new self();

        foreach ($data as $k=>$v){
            $update_company[] = [
                'vendor_id'=>$v['vendor_id'],
                'id'=>$v['id'],
            ];
        }

        $result = $productClass->isUpdate(true)->saveAll($update_company);
        if($result===0){
            return ['status'=>0,'result'=>'更新供应商失败'];
        }
        return ['status'=>1,'result'=>'更新供应商成功'];

    }

    public static function addMark($pid,$mark)
    {
        $productMarkClass=new ProductMark();
        $list=Db::name('mark')->where('del_flag',0)->column('id','mark_text');
        $ids=[];
        foreach ($mark['checkedMarks'] as $k=>$v){
            $id=$list[$v];
            array_push($ids,$id);
        }
        $data=[];
        $i=0;
        foreach ($pid as $k=>$v){
            foreach ($ids as $x=>$y){
                $data[$i]['pro_id']=$v;
                $data[$i]['mark_id']=$y;
                $i++;
            }
        }
        $productMarkClass->startTrans();
        try {
            $productMarkClass->where('pro_id','in',$pid)->update(['del_flag'=>1]);
            $rows=$productMarkClass->where('pro_id','in',$pid)->select()->toArray();
            $list=[];
            foreach ($rows as $k=>$v){
                $list[$v['pro_id']][]=$v;
            }
            $arr_update=[];
            $arr_add=[];
            foreach($data as $k=>$v){
                if (isset($list[$v['pro_id']])){
                    $arr=array_column($list[$v['pro_id']],'id','mark_id');
                    if (isset($arr[$v['mark_id']])){
                        array_push($arr_update,$arr[$v['mark_id']]);
                    }else{
                        $arr_add[]=['pro_id'=>$v['pro_id'],'mark_id'=>$v['mark_id']];
                    }
                }else{
                    $arr_add[]=['pro_id'=>$v['pro_id'],'mark_id'=>$v['mark_id']];
                }
            }
            $result=$productMarkClass->where('id','in',$arr_update)->update(['del_flag'=>0]);
            if ($result===false){
                return ['status'=>false,'result'=>'标签添加失败'];
            }
            $result=$productMarkClass->isUpdate(false)->saveAll($arr_add);
            if (!$result){
                return ['status'=>false,'result'=>'标签添加失败'];
            }
            $productMarkClass->commit();
            return ['status'=>true,'result'=>'标签添加成功'];
        }catch (\Exception $e){
            $productMarkClass->rollback();
            trace('标签添加失败'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'标签添加失败'];
        }

    }

    public static function getProductByNotice($id)
    {
        $productClass=new self();
        $productMarkClass=new ProductMark();
        $rows=$productMarkClass->alias('p')
            ->join('mark m','m.id=p.mark_id','left')
            ->where(['p.del_flag'=>0,'m.del_flag'=>0])
            ->field('p.id,p.pro_id,p.mark_id,m.mark_text')
            ->select()->toArray();
        $data=$productClass
            ->alias('p')
            ->join('notice_product n','n.pro_id=p.id')
            ->where('n.notice_id',$id)
            ->field('p.id,p.cn_name,p.en_name,p.pur_price,p.amount,p.image,p.introduction')
            ->select()->toArray();
        $list=[];
        foreach ($rows as $k=>$v){
            $list[$v['pro_id']][]=$v;
        }
        foreach($data as $k=>$v){
            if (isset($list[$v['id']])){
                $data[$k]['mark']=$list[$v['id']];
            }else{
                $data[$k]['mark']=[];
            }
        }
        return ['status'=>true,'result'=>$data];
    }

    public static function getProduct($id)
    {
        $productClass=new self();
        $productMarkClass=new ProductMark();
        $data=$productClass
            ->where('id',$id)
            ->field('id,cn_name,en_name,remark')
            ->find();
        $mark_id=$productMarkClass->where('pro_id',$id)->column('mark_id');
        foreach ($mark_id as $k=>$v){
            $mark_id[$k]=(string)$v;
        }
        $data['mark_id']=$mark_id;
        return ['status'=>true,'result'=>$data];
    }

    public static function cancelOrderDemandStock($id){
        $OrderItemClass=new OrderItem();
        $ProductClass=new self();
        $OrderItemDetailClass=new OrderItemDetail();

        $ProductClass->startTrans();
        try {
            $pro_ids = [];
            $old_item_data = $OrderItemClass->where('order_id', $id)->where('del_flag', 0)->lock(true)->field('amount,demand_stock,pro_id,id')->select()->toArray();
            $old_item_list = [];
            $old_item_id = [];
            foreach ($old_item_data as $key => $value) {
                if (!$value['pro_id']) {
                    $old_item_id[] = $value['id'];
                } else {
                    $pro_ids[] = $value['pro_id'];
                }
                if (isset($old_item_list[$value['pro_id']])) {
                    $old_item_list[$value['pro_id']]['amount'] += $value['amount'];
                    $old_item_list[$value['pro_id']]['demand_stock'] += $value['demand_stock'];
                    continue;
                }
                $old_item_list[$value['pro_id']]['amount'] = $value['amount'];
                $old_item_list[$value['pro_id']]['demand_stock'] = $value['demand_stock'];
            }
            if (!empty($old_item_id)) {
                $old_item_detail_list = $OrderItemDetailClass->where('order_item_id', 'in', $old_item_id)->where('del_flag', 0)->lock(true)->group('pro_id')->column('sum(amount) amount,sum(demand_stock) demand_stock', 'pro_id');
                if (!empty($old_item_detail_list)) {
                    $old_pro_ids = array_keys($old_item_detail_list);
                    $pro_ids = array_unique(array_merge($pro_ids, $old_pro_ids));
                }
            }
            $stock_list = $ProductClass->where('id', 'in', $pro_ids)->lock(true)->column('amount,demand_stock,locked_demand_stock,type', 'id');
            foreach ($stock_list as $key => $value) {
                if ($value['type'] === 1) {
                    if (isset($old_item_list[$value['id']])) {
                        $value['demand_stock'] -= $old_item_list[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_item_list[$value['id']]['demand_stock'];
                    }
                    if (isset($old_item_detail_list[$value['id']])) {
                        $value['demand_stock'] -= $old_item_detail_list[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_item_detail_list[$value['id']]['demand_stock'];
                    }
                }
                $stock_list[$key] = $value;
            }
            $result=$ProductClass->isUpdate()->allowField(['id','demand_stock','locked_demand_stock'])->saveAll($stock_list);
            if($result===false){
                throw Exception('回退库存失败');
            }

            $ProductClass->commit();
            return ['status'=>true,'result'=>'退回成功'];
        }catch (Exception $e){
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'退回失败'.$e->getMessage()];
        }
    }
}